require "FileUtils"
require "timeout"

module Cpg
  class App
    
    attr_accessor :bundleIdentifier, :category, :contact, :date, :description,
                  :location, :maintainer, :name, :scripts, :size, :source, :version
                  
    def fetch
      if Dir.glob("source").empty?
        Dir.mkdir("source")
      end
      
      if File.exist?("source/#{name}.zip")
        return true
      end
      
      print "fetch #{location} .."
      
      begin
        
        Timeout::timeout(90) do |timeout_length|
          File.open("source/#{name}.zip","wb") do |file|
            options = {"User-Agent" => "AppTapp/3.0.1"}
            file << open(location, options).read
          end
        
          puts "[OK]"
          return true
        end
      rescue Timeout::Error
        if File.exist?("source/#{name}.zip")
          File.delete("source/#{name}.zip")
        end
        puts "[FAILED:Timeout]"
        return false
      rescue
        if File.exist?("source/#{name}.zip")
          File.delete("source/#{name}.zip")
        end
        puts "[FAILED]"
        return false
      end
      
    end
  end
end
